package org.example.managere.service.feibiao.impl;

import org.example.managere.dto.feibiao.AmArchivesOperationTestDto;
import org.example.managere.entity.feibiao.AmArchivesBase;
import org.example.managere.entity.feibiao.AmArchivesOperationTest;
import org.example.managere.repository.feibiao.AmArchivesBaseRepository;
import org.example.managere.repository.feibiao.AmArchivesOperationTestRepository;
import org.example.managere.service.feibiao.AmArchivesOperationTestService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 电机性能试验数据服务实现类
 */
@Service
public class AmArchivesOperationTestServiceImpl implements AmArchivesOperationTestService {

    private final AmArchivesOperationTestRepository operationTestRepository;
    private final AmArchivesBaseRepository baseRepository;

    @Autowired
    public AmArchivesOperationTestServiceImpl(
            AmArchivesOperationTestRepository operationTestRepository,
            AmArchivesBaseRepository baseRepository) {
        this.operationTestRepository = operationTestRepository;
        this.baseRepository = baseRepository;
    }

    @Override
    @Transactional
    public AmArchivesOperationTestDto save(AmArchivesOperationTestDto operationTestDto) {
        AmArchivesOperationTest operationTest = new AmArchivesOperationTest();
        
        // 通过motorId关联电机基本信息
        String motorId = operationTestDto.getMotorId();
        Optional<AmArchivesBase> baseOptional = baseRepository.findById(motorId);
        AmArchivesBase motorBase = baseOptional.orElseThrow(() -> 
            new IllegalArgumentException("电机不存在，ID: " + motorId));
        
        // 复制基本属性
        BeanUtils.copyProperties(operationTestDto, operationTest);
        operationTest.setMotorId(motorBase);
        
        // 保存实体
        operationTest = operationTestRepository.save(operationTest);
        
        // 转换为DTO并返回
        return convertToDto(operationTest);
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<AmArchivesOperationTestDto> findById(Integer testId) {
        return operationTestRepository.findById(testId)
                .map(this::convertToDto);
    }

    @Override
    @Transactional
    public AmArchivesOperationTestDto update(AmArchivesOperationTestDto operationTestDto) {
        if (!operationTestRepository.existsById(operationTestDto.getTestId())) {
            throw new IllegalArgumentException("无法更新不存在的记录，ID: " + operationTestDto.getTestId());
        }
        return save(operationTestDto);
    }

    @Override
    @Transactional
    public void deleteById(Integer testId) {
        operationTestRepository.deleteById(testId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<AmArchivesOperationTestDto> findAll() {
        return operationTestRepository.findAll().stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public Page<AmArchivesOperationTestDto> findAll(Pageable pageable) {
        Page<AmArchivesOperationTest> operationTestPage = operationTestRepository.findAll(pageable);
        List<AmArchivesOperationTestDto> dtoList = operationTestPage.getContent().stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
        return new PageImpl<>(dtoList, pageable, operationTestPage.getTotalElements());
    }

    @Override
    @Transactional(readOnly = true)
    public List<AmArchivesOperationTestDto> findByMotorId(String motorId) {
        return operationTestRepository.findByMotorId_MotorId(motorId).stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public List<AmArchivesOperationTestDto> findByTestType(String testType) {
        return operationTestRepository.findByTestType(testType).stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public List<AmArchivesOperationTestDto> findByTestTimeBetween(Date startTime, Date endTime) {
        return operationTestRepository.findByTestTimeBetween(startTime, endTime).stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public List<AmArchivesOperationTestDto> findLatestTestsByMotorId(String motorId, int limit) {
        return operationTestRepository.findLatestTestsByMotorId(motorId, org.springframework.data.domain.PageRequest.of(0, limit))
                .stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    /**
     * 将实体转换为DTO
     */
    private AmArchivesOperationTestDto convertToDto(AmArchivesOperationTest operationTest) {
        AmArchivesOperationTestDto dto = new AmArchivesOperationTestDto();
        BeanUtils.copyProperties(operationTest, dto);
        
        // 设置关联的电机ID
        if (operationTest.getMotorId() != null) {
            dto.setMotorId(operationTest.getMotorId().getMotorId());
            
            // 设置额外的电机信息
            dto.setMotorType(operationTest.getMotorId().getMotorType());
            dto.setManufacturer(operationTest.getMotorId().getManufacturer());
        }
        
        return dto;
    }
} 